package org.javason.util;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;

public class MetricsInterceptor implements MethodInterceptor {
	public static final String VERSION = "$Rev: 61885 $";
	private boolean _outputArguments = true;
	
	
	public void setOutputArguments(boolean outputArguments) {
		_outputArguments = outputArguments;
	}
	
    public Object invoke(MethodInvocation invocation) throws Throwable {
		Metrics timer = Metrics.beginCollection();
        
		StringBuilder args = new StringBuilder();
		if (_outputArguments && invocation.getArguments() != null) {
			for (Object arg : invocation.getArguments()) {
				args.append(ReflectionToStringBuilder.toString(arg));
			}
		}
		Object rval = null;
		
		try {
			rval = invocation.proceed();
		} finally {
			timer.endCollection();
		}
		
        if (_outputArguments && invocation.getArguments() != null) {
        	timer.logMethodCall(invocation.getClass().getCanonicalName(),
            		invocation.getMethod().getName(),
            		args.toString());
        } else {
        	timer.log(String.format(Metrics.FORMAT, 
        		invocation.getClass().getCanonicalName(),
        		invocation.getMethod().getName()));
        }
    	return rval;
    }
}

